import { PropsWithChildren, RefObject } from 'react';

import { ReactComponent as Settings } from '@/assets/images/shared/icon-settings.svg';
import { SelectProps } from '@/shared/interfaces';
import { useKeyboard, useParams } from '@/shared/lib/hooks';
import { Button, ButtonVariants, Modal, Select, Tag } from '@/shared/ui';
import cn from 'classnames';
import dynamic from 'next/dynamic';

import { FilterProps, InputFocusProps } from '../lib/useFilters';
import { FilterModal } from './FilterModal';
import cs from './Filters.module.scss';
import { SearchLoader } from './Search';

const SearchInput = dynamic(() => import('./Search'), {
  ssr: false,
  loading: () => <SearchLoader />,
});

export const Filters = ({
  children,
  topics,
  isInputMode,
  inputRef,
  formats,
  searchClassName,
  selectedPool,
  handleSaveNewFilters,
  handlePoolSelect,
  isFiltersOpen,
  handleClearFilters,
  handleOpenModal,
  handleCloseModal,
  handleCancelSearch,
  onFocus,
  onBlur,
}: {
  topics?: SelectProps[];
  formats?: SelectProps[];
  searchClassName?: string;
  inputRef?: RefObject<HTMLInputElement>;
  isInputMode?: boolean;
} & InputFocusProps &
  FilterProps &
  PropsWithChildren) => {
  const [, setValue] = useParams<string>({ key: 'search', deserialize: (v) => v || '' });
  const handleCancel = () => {
    setValue(() => '');
    handleCancelSearch();
    inputRef?.current?.blur();
  };
  useKeyboard('Escape', handleCancel);
  return (
    <>
      <div
        className={cn(
          cs.container,
          selectedPool.length > 7 && cs.container_bigger,
          (isInputMode || !selectedPool.length) && cs.container_selected,
        )}
      >
        <div className={cs.filters_container}>
          <div className={cs.filters}>
            <>
              <Select
                className={cs.select_title}
                config={{ title: 'Тема', values: topics }}
                containerClassName={cn(cs.desktop, isInputMode && 'hidden')}
                disabled={!topics}
                onSelect={(v) => handlePoolSelect({ ...v, arr: 'topics' })}
                placeholderClassName={null}
                selected={selectedPool.filter((v) => v.arr === 'topics')}
                width={182}
                withCheckmark
                withPlaceholder="Тема"
              />
              <Select
                className={cs.select_title}
                config={{ title: 'Формат', values: formats }}
                containerClassName={cn(cs.desktop, isInputMode && 'hidden')}
                disabled={!formats}
                onSelect={(v) => handlePoolSelect({ ...v, arr: 'formats' })}
                placeholderClassName={null}
                selected={selectedPool.filter((v) => v.arr === 'formats')}
                width={182}
                withCheckmark
                withPlaceholder="Формат"
              />
            </>

            <div className={cn(cs.search, searchClassName, isInputMode && cs.active)}>
              <SearchInput innerRef={inputRef} onBlur={onBlur} onFocus={onFocus} />
            </div>
            <Button
              aria-label="Отмена"
              className={cn(cs.cancel, !isInputMode && 'hidden')}
              onClick={handleCancel}
              variant={ButtonVariants.Link}
            >
              Отмена
            </Button>
            <div className={cn(cs.icon_settings, isFiltersOpen && cs.icon_settings_no_hover, isInputMode && 'hidden')}>
              <Settings onClick={handleOpenModal} />
            </div>
          </div>

          {children}
        </div>
        {!!selectedPool.length && (
          <div className={cn(cs.selected, isInputMode && cs.hidden_selected)}>
            {selectedPool.map((tag) => (
              <Tag isSelected key={tag.id + tag.arr} onClick={() => handlePoolSelect(tag)} tag={tag.title} withCross />
            ))}
            {selectedPool.length > 1 && <Tag onClick={handleClearFilters} tag="Очистить все" variant="secondary" />}
          </div>
        )}
      </div>

      <Modal isMobile isOpen={isFiltersOpen} onCloseClick={handleCloseModal}>
        <FilterModal
          formats={formats?.map((v) => ({ ...v, arr: 'formats' }))}
          handleSaveNewFilters={handleSaveNewFilters}
          selectedFilters={selectedPool}
          topics={topics?.map((v) => ({ ...v, arr: 'topics' }))}
        />
      </Modal>
    </>
  );
};
